#include "wordeditdialog.h"
#include "logutil.h"

#include <QVBoxLayout>
#include <QFormLayout>
#include <QMessageBox>

WordEditDialog::WordEditDialog(bool isAdd, const QString &cnWord, const QString &twWord, QWidget *parent)
    : QDialog(parent)
    , m_isAdd(isAdd)
    , m_opencc(OpenCCUtil::getInstance())
    , m_userDict(UserDict::getInstance())
{
	initUI();
	// 修改模式 填充原有词
	if (!isAdd) {
		m_cnEdit->setText(cnWord);
        m_twEdit->setText(twWord);
        m_cnEdit->setReadOnly(true); // 修改时简体词不可编辑
	}
}

void WordEditDialog::onConfirmClicked()
{
	// check post make sure
	if (!validateInput())	return;
	QString cnWord = getCnWord();
    QString twWord = getTwWord();

	if (m_isAdd) {
		// 去重
		if (m_userDict->isWordExists(cnWord)) {
            QMessageBox::warning(this, "提示", "该简体词已存在");
            return;
        }
		// add dic
		m_userDict->addWord(cnWord, twWord);
        LogUtil::info(QString("[WordEditDialog] 添加自定义词：%1（繁体：%2）").arg(cnWord).arg(twWord));
	} else {
        // 修改词库
        m_userDict->updateWord(cnWord, twWord);
        LogUtil::info(QString("[WordEditDialog] 修改自定义词：%1（新繁体：%2）").arg(cnWord).arg(twWord));
    }
    accept(); // 关闭弹窗
}

void WordEditDialog::initUI()
{
	setWindowTitle(m_isAdd ? "添加自定义词" : "修改自定义词");
    setFixedSize(350, 200);
    setStyleSheet(R"(
        QDialog { background-color: white; border-radius: 8px; }
        QLabel { font-size: 13px; color: #666; }
        QLineEdit { height: 30px; border: 1px solid #E0E0E0; border-radius: 4px; padding: 0 8px; }
        QPushButton { height: 35px; border-radius: 4px; border: none; font-size: 13px; }
        QPushButton#GenerateBtn { background-color: #F5F7FA; color: #333; }
        QPushButton#ConfirmBtn { background-color: #1890FF; color: white; }
    )");

	// 布局  简体词 + 繁体词
	QVBoxLayout *mainLayout = new QVBoxLayout(this);
    mainLayout->setContentsMargins(20, 20, 20, 20);
    mainLayout->setSpacing(15);

	m_cnEdit = new QLineEdit();
    m_cnEdit->setPlaceholderText("输入简体词");
    formLayout->addRow("简体词：", m_cnEdit);

    m_twEdit = new QLineEdit();
    m_twEdit->setPlaceholderText("自动生成或手动输入");
    m_twEdit->setEnabled(false); // 默认禁用，生成后可修改
    formLayout->addRow("繁体词：", m_twEdit);
    mainLayout->addLayout(formLayout);

    // 按钮布局：生成繁体 + 确认
    QHBoxLayout *btnLayout = new QHBoxLayout();
    QPushButton *generateBtn = new QPushButton("自动生成繁体");
    generateBtn->setObjectName("GenerateBtn");
    connect(generateBtn, &QPushButton::clicked, this, &WordEditDialog::onGenerateTraditionalClicked);
    btnLayout->addWidget(generateBtn);

    QPushButton *confirmBtn = new QPushButton(m_isAdd ? "添加" : "修改");
    confirmBtn->setObjectName("ConfirmBtn");
    connect(confirmBtn, &QPushButton::clicked, this, &WordEditDialog::onConfirmClicked);
    btnLayout->addWidget(confirmBtn);
    mainLayout->addLayout(btnLayout);
}

bool WordEditDialog::validateInput()
{
	QString cnWord = getCnWord();
    QString twWord = getTwWord();

    // 简体词非空
    if (cnWord.isEmpty()) {
        QMessageBox::warning(this, "提示", "简体词不能为空");
        return false;
    }

    // 仅允许中文
    QRegExp chineseReg("^[\u4e00-\u9fa5]+$");
    if (!chineseReg.exactMatch(cnWord)) {
        QMessageBox::warning(this, "提示", "简体词仅允许中文");
        return false;
    }
    if (!chineseReg.exactMatch(twWord)) {
        QMessageBox::warning(this, "提示", "繁体词仅允许中文");
        return false;
    }

    return true;
}

void WordEditDialog::onGenerateTraditionalClicked() {
	// 自动生成繁体
	QString cnWord = m_cnEdit->text().trimmed();
    if (cnWord.isEmpty()) {
        QMessageBox::warning(this, "提示", "请先输入简体词");
        return;
    }

	// 调用OpenCC生成台繁
    QString twWord = m_opencc->convert(cnWord, OpenCCUtil::ConvertDirection::S2T_TW);
    if (twWord.isEmpty()) {
        QMessageBox::critical(this, "错误", "简繁转换失败，请检查OpenCC配置");
        return;
    }

    m_twEdit->setText(twWord);
    m_twEdit->setEnabled(true); // 允许手动修改
}